<template>
  <div class="page-mobile_my-certificate">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="我的证书"
    ></white-header>
    <div class="certificate-list">
      <div
        class="certificate-item"
        v-for="(item, index) in certificateList"
        :key="index"
      >
        <div class="certificate-left">
          <p>姓&emsp;&emsp;名：{{ item.name }}</p>
          <p>证书编号：{{ item.certificateNo }}</p>
          <p>证书类型：{{ item.certificateTypeName }}</p>
        </div>
        <!-- <div
          class="certificate-right"
          @click="previewFile(item.url, item.certificateNo)"
        >
          预览
        </div> -->
        <div
          class="certificate-right"
          @click="downloadExport(item.url, item.certificateNo)"
        >
          下载
        </div>
      </div>
    </div>
    <div class="footer" v-show="certificateList.length > 0">
      <span class="tips">我是有底线的</span>
    </div>
    <van-empty description="暂无证书哟~" v-show="certificateList.length <= 0" />
    <div class="preview-file-dialog" v-if="previewFileDialog">
      <pdf
        class="preview-pdf"
        v-if="previewFileType == 1"
        ref="pdf"
        :src="previewFileUrl"
        :page="currentPage"
        @num-pages="pageCount = $event"
        @page-loaded="currentPage = $event"
        @loaded="loadPdfHandler"
      >
      </pdf>
      <p class="preview-arrow" v-if="previewFileType == 1">
        <span
          @click="changePdfPage(0)"
          class="turn"
          :class="{ grey: currentPage == 1 }"
          >上一页</span
        >
        <span style="margin:0 20px;">{{ currentPage }} / {{ pageCount }}</span>
        <span
          @click="changePdfPage(1)"
          class="turn"
          :class="{ grey: currentPage == pageCount }"
          >下一页</span
        >
      </p>
      <img
        class="preview-img"
        v-if="previewFileType == 2"
        :src="previewFileUrl"
        alt=""
      />
      <Icon type="md-close close-preview" @click="previewFileDialog = false" />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { downloadReport, getMyCertificate } from "~/api/course";
export default {
  name: "my-certificate",
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader
  },
  data() {
    return {
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      pdfPages: 0, //pdf页数
      vuePdf: null, //vue-pdf对象
      previewFileDialog: false, //预览窗口弹窗
      previewFileType: 1, //1:pdf 2:文件
      // 预览文件地址
      previewFileUrl: null,
      certificateList: []
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      },
      token(state) {
        return state.token;
      }
    })
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--;
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++;
        // console.log(this.currentPage)
      }
    },

    // pdf加载时
    loadPdfHandler(e) {
      this.$nextTick(() => {
        this.currentPage = 1; // 加载的时候先加载第一页
      });
    },
    // 证书预览
    async previewFile(url, certificateNo) {
      if (/\.pdf/.test(url)) {
        console.log("是pdf文件");
        this.previewFileType = 1;
        this.previewFileUrl = url;
        let CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/cmaps/"
        let loadingTask = this.vuePdf.default.createLoadingTask({
          url: url,
          cMapUrl: CMAP_URL,
          cMapPacked: true,
        });
        loadingTask.promise
          .then(pdf => {
            this.pdfPages = pdf.numPages;
            this.pageCount = pdf.numPages;
          })
          .catch(err => {
            console.error("pdf 加载失败", err);
          });
      } else {
        console.log("是图片");
        this.previewFileType = 2;
        this.previewFileUrl = url;
      }

      // this.previewFileUrl = url;
      this.previewFileDialog = true;
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
          time = parseInt(time);
        } else if (typeof time === "string") {
          time = time.replace(new RegExp(/-/gm), "/");
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
          return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return time_str;
    },
    onConfirm(value) {
      this.typeValue = value.text;
      this.form.type = value.id;
      if (value.id == 1) {
        this.form.name = "";
        this.form.idNumber = "";
      } else {
        this.form.certificateNo = "";
      }
      this.showPicker = false;
    },
    //证书下载
    async downloadExport(url, reportName) {
      this.SET_IS_LOADING(true);

      let result = await downloadReport(url);
      const content = result.data;
      const blob = new Blob([content]);
      let fileName = reportName + "." + url.replace(/(.*\.)/, ""); // 自定义文件名+后缀;
      if ("download" in document.createElement("a")) {
        console.log("非IE下载");
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        console.log("IE10+下载");
        navigator.msSaveBlob(content, fileName);
      }
      this.SET_IS_LOADING(false);
    },
    //获取我的证书
    async getMyCertificate() {
      this.SET_IS_LOADING(true);
      let result = await getMyCertificate(this.user_info.id);
      if (result && result.data && result.data.code == 200) {
        this.certificateList = result.data.data;
      } else {
        this.$toast({
          message: "获取失败",
          icon: "warn-o"
        });
      }
      this.SET_IS_LOADING(false);
    },
    async searchCertificate() {
      let params = {};
      if (this.form.type == 1) {
        if (!(this.form.certificateNo && this.form.certificateNo.trim())) {
          this.$toast({
            message: "请填写证书编号",
            icon: "warn-o"
          });
          return;
        }
        if (!/^[0-9a-zA-Z_\-\.]{1,}$/.test(this.form.certificateNo)) {
          this.$toast({
            message: "请输入正确的证书编号",
            icon: "warn-o"
          });
          return;
        }
        params = {
          certificateNo: this.form.certificateNo
        };
      } else {
        if (!(this.form.name && this.form.name.trim())) {
          this.$toast({
            message: "请填写姓名",
            icon: "warn-o"
          });
          return;
        }
        if (!this.form.idNumber) {
          this.$toast({
            message: "请填写身份证",
            icon: "warn-o"
          });
          return;
        }
        if (
          !/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            this.form.idNumber
          )
        ) {
          this.$toast({
            message: "请输入正确的身份证",
            icon: "warn-o"
          });
          return;
        }
        params = {
          name: this.form.name,
          idNumber: this.form.idNumber
        };
      }
      this.SET_IS_LOADING(true);
      let result = await searchCertificate(params);
      if (result && result.data && result.data.code == 200) {
        this.certificateList = result.data.data;
        this.$toast({
          message: "查询成功",
          icon: "passed"
        });
      } else {
      }
      this.SET_IS_LOADING(false);
    }
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      } else {
        this.getMyCertificate();
        this.setDisabled(false);
        this.refreshFun(() => {
          this.setLoading(false);
          this.getMyCertificate();
        });
      }
    }
  },
  deactivated() {
    this.setDisabled(true);
  },
  destroyed() {
    this.setDisabled(true);
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      } else {
        this.getMyCertificate();
        this.setDisabled(false);
        this.refreshFun(() => {
          this.setLoading(false);
          this.getMyCertificate();
        });
      }
      this.vuePdf = require("vue-pdf");
    }
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.page-mobile_my-certificate {
  width: 7.2rem;
  min-height: 100vh;
  background-color: #f2f3f5;
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
  .preview-file-dialog {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 7.2rem;
    height: 100%;
    background: #fff;
    z-index: 10000000000000000;
    overflow: auto;
    .preview-btn {
      font-size: 0.3rem;
      cursor: pointer;
      color: var(--theme-color);
    }
    .close-preview {
      position: fixed;
      right: 0.3rem;
      top: 0.3rem;
      font-size: 0.6rem;
      cursor: pointer;
    }
    .preview-img {
      position: absolute;
      left: 0;
      // top: 0;
      right: 0;
      // bottom: 0;
      padding: 0.3rem 0;
      max-width: 6.9rem;
      margin: auto;
    }
    .preview-pdf {
      width: 7.2rem;
      margin: 0 auto;
    }
    .preview-arrow {
      padding: 0.3rem 0;
      text-align: center;
      font-size: 0.3rem;
      .turn {
        cursor: pointer;
      }
    }
  }
  .certificate-list {
    .certificate-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 7.2rem;
      box-sizing: border-box;
      background: #ffffff;
      font-size: 0.3rem;
      border-bottom: 1px solid #e6e6e6;
      padding: 0.1rem;
      &:last-child {
        border-bottom: none;
      }
      .certificate-left {
        width: 80%;
        p {
          margin: 0.1rem 0;
        }
      }
      .certificate-right {
        width: 20%;
        text-align: center;
        color: var(--theme-color);
      }
    }
  }
}
</style>
<style lang="scss">
.page-mobile_my-certificate {
}
</style>
